#!/usr/bin/env python
import os
from subprocess import Popen, PIPE
import sys
def compiler_path():
    paths = ""
    command = "echo | gcc -v -x c++ -E -"
    flag = 0
    p = Popen(command,shell=True,stderr=PIPE,stdout=PIPE)
    p.wait()
    lines = p.stderr.read().split("\n")
    for s in lines:
        if s.startswith("#include <...> search starts here"):
            flag = 1
            continue
        if s.startswith("End of search list."):
            flag = 0
        if flag == 1:
            paths += "-I" + s.lstrip() + "\n"
    return paths

def searchPath():
    paths = ""
    curpath = os.path.dirname(os.getcwd())
    for root,dirs,files in os.walk(curpath):
        for dir in dirs:
            dir = os.path.join(root, dir)
            reldir = os.path.relpath(dir)
            if reldir.startswith(".") <= 0:
                lists = os.listdir(dir)
                for l in lists:
                    if os.path.isfile(os.path.join(dir,l)):
                        name,ext = os.path.splitext(l)
                        if len(ext) > 0:
                            if ext == ".h" or ext == ".hpp":
                                paths += "-I" + reldir + "\n"
                                break

    return paths
def main():
    paths = "-DDEBUG\n"
    paths += compiler_path()
    paths += searchPath()
    fp = open(".clang_complete","w")
    fp.write(paths)
    fp.close()

if __name__ == '__main__':
    main()
